<template>
	<BasicDrawer title="角色权限" @register="register" width="420" showFooter @ok="handleSubmit">
		<div class="pl-2 mb-2">角色名称：{{ roleName }}</div>
		<!-- <Tree
			:tree-data="menuTree"
			:fieldNames="{ key: 'menuId' }"
			checkable
			:checked-keys="checkedKeys"
			@check="onCheck"
		></Tree> -->
		<BasicTree
			:treeData="menuTree"
			:fieldNames="{ key: 'menuId' }"
			checkable
			:checked-keys="checkedKeys"
			@check="onCheck"
			toolbar
			title="菜单分配"
		/>
	</BasicDrawer>
</template>

<script setup lang="ts">
import { BasicDrawer, BasicTree } from '#/components';
import { useDrawerInner } from '#/hooks';
import { ref } from 'vue';
import { setMenuByRoleId, getMenuByRoleId } from '@/api/sys/role';
// import { Tree } from 'ant-design-vue';
import { useMessage } from '@/hooks/web/useMessage';
import { getAllMenuTree } from '@/api/sys/menu';

let roleName = ref('');
let roleId = ref();
let menuTree = ref([]);
let checkedKeys = ref<any>([]);
let checkedKeysResult = ref();

const [register, { closeDrawer }] = useDrawerInner(data => {
	roleName.value = data.record.roleName;
	roleId.value = data.record.roleId;
	getAllMenuTree().then(res => {
		menuTree.value = res;
		initCheckedMenus();
	});
});

function initCheckedMenus() {
	getMenuByRoleId(roleId.value).then(res => {
		const keys = res.map(({ menuId }) => Number(menuId));

		checkedKeys.value = keys;
		checkedKeysResult.value = keys;
	});
}

function onCheck(checkedKeys1, info: Recordable) {
	checkedKeys.value = checkedKeys1;
	checkedKeysResult.value = [...checkedKeys1, ...info.halfCheckedKeys];
}

const { createMessage } = useMessage();
const emit = defineEmits(['success', 'register']);
async function handleSubmit() {
	try {
		const params = {
			roleId: roleId.value,
			menuIds: checkedKeysResult.value,
		};
		await setMenuByRoleId(params);
		closeDrawer();
		emit('success');
	} catch (_err) {
		createMessage.error('操作失败');
	}
}
</script>

<style scoped lang="less"></style>
